package com.sz.common.base.dao;

import com.sz.common.base.utils.ReflectHelper;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Function: 分页插件<br>
 * Author: hpeng.wang<br>
 * Date: 2016-11-01 14:11:00
 */
@Intercepts({@Signature(
        type = StatementHandler.class,
        method = "prepare",
        args = {Connection.class, Integer.class
        })})
public class PagePlugin implements Interceptor {
    private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
    private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
    private static final ReflectorFactory DEFAULT_REFLECTOR_FACTORY = new DefaultReflectorFactory();
    public static final String MYSQL = "mysql";
    public static final String ORACLE = "oracle";

    private static String dialect = "mysql"; // 数据库类型(默认为mysql)
    private static String pageSqlId = ".*ListPage.*"; // 需要拦截的ID(正则匹配)
    //private Logger logger = Logger.getLogger(getClass());

    /**
     * 计算分页参数，从页得到分页的sql.
     *
     * @param ivk 参数
     * @return 分页对象
     * @throws Throwable 错误
     */
    @Override
    public Object intercept(Invocation ivk) throws Throwable {
        if (ivk.getTarget() instanceof RoutingStatementHandler) {
            RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();
            BaseStatementHandler delegate = (BaseStatementHandler)
                    ReflectHelper.getValueByFieldName(statementHandler, "delegate");
            MappedStatement mappedStatement = (MappedStatement)
                    ReflectHelper.getValueByFieldName(delegate, "mappedStatement");
            // 对新增和修改字符串的字段进行trim处理
            if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT ||
                    mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE) {
                BoundSql boundSql = delegate.getBoundSql();
                Object parameterObject = boundSql.getParameterObject();
                Class cls = parameterObject.getClass();
                Field[] fields = cls.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    Field f = fields[i];
                    f.setAccessible(true);
                    if ("java.lang.String".equals(f.getType().getName())) {
                        Object obj = f.get(parameterObject);
                        String val = obj == null ? null : ((String) obj).trim();
                        f.set(parameterObject, val);
                    }
                }
            }

            if (mappedStatement.getId().matches(pageSqlId)) { //拦截需要分页的SQL
                BoundSql boundSql = delegate.getBoundSql();
                Object parameterObject = boundSql.getParameterObject();
                //分页SQL<select>中parameterType属性对应的实体参数，即Mapper接口中执行分页方法的参数,该参数不得为空

                ParamData paramData = (ParamData) parameterObject;

                if (parameterObject == null) {
                    throw new NullPointerException("parameterObject尚未实例化！");
                } else {
                    Connection connection = (Connection) ivk.getArgs()[0];
                    String sql = boundSql.getSql();
                    //String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //记录统计
                    String countSql = "select count(0) from (" + sql + ")  tmp_count"; //记录统计 ==
                    // oracle 加 as 报错(SQL command not properly ended)
                    PreparedStatement countStmt = connection.prepareStatement(countSql);
                    BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(),
                            countSql, boundSql.getParameterMappings(), parameterObject);


                    MetaObject metaBoundSql = MetaObject.forObject(boundSql, DEFAULT_OBJECT_FACTORY,
                            DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
                    Object additionalParameters = metaBoundSql.getValue("additionalParameters");
                    if (additionalParameters != null && additionalParameters instanceof Map) {
                        HashMap<String, Object> map = (HashMap) additionalParameters;
                        map.forEach(countBoundSql::setAdditionalParameter);
                    }

                    setParameters(countStmt, mappedStatement, countBoundSql, parameterObject);
                    ResultSet rs = countStmt.executeQuery();
                    int count = 0;
                    if (rs.next()) {
                        count = rs.getInt(1);
                    }
                    rs.close();
                    countStmt.close();
                    Pagination pagination = paramData.getPagination();

                    if (pagination != null) {    //参数就是Page实体
                        pagination.setTotalResult(count);
                    } else {    //参数为某个实体，该实体拥有Page属性
                        Field pageField = ReflectHelper.getFieldByFieldName(parameterObject,
                                "pagination");
                        if (pageField != null) {
                            pagination = (Pagination)
                                    ReflectHelper.getValueByFieldName(parameterObject,
                                            "pagination");
                            if (pagination == null) {
                                pagination = new Pagination();
                            }
                            pagination.setTotalResult(count);
                            ReflectHelper.setValueByFieldName(parameterObject, "pagination",
                                    pagination); //通过反射，对实体对象设置分页对象
                        } else {
                            throw new NoSuchFieldException(parameterObject.getClass()
                                    .getName() + "不存在 pagination 属性！");
                        }
                    }
                    String pageSql = generatePageSql(sql, pagination);
                    ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql);
                    //将分页sql语句反射回BoundSql.
                }
            }
        }
        return ivk.proceed();
    }


    /**
     * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
     *
     * @param ps              preparedStatement
     * @param mappedStatement mappedStatement
     * @param boundSql        boundSql
     * @param parameterObject parameterObject
     * @throws SQLException sql异常
     */
    private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql
            boundSql, Object parameterObject) throws SQLException {
        ErrorContext.instance().activity("setting parameters").object(mappedStatement
                .getParameterMap().getId());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (parameterMappings != null) {
            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            MetaObject metaObject =
                    parameterObject == null ? null : configuration.newMetaObject(parameterObject);
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                    if (parameterObject == null) {
                        value = null;
                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql
                            .hasAdditionalParameter(prop.getName())) {
                        value = boundSql.getAdditionalParameter(prop.getName());
                        if (value != null) {
                            value = configuration.newMetaObject(value).getValue(propertyName
                                    .substring(prop.getName().length()));
                        }
                    } else {
                        value = metaObject == null ? null : metaObject.getValue(propertyName);
                    }
                    TypeHandler typeHandler = parameterMapping.getTypeHandler();
                    if (typeHandler == null) {
                        throw new ExecutorException("There was no TypeHandler found for parameter"
                                + " " + propertyName + " of statement " + mappedStatement.getId());
                    }
                    typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType() == null ? JdbcType.VARCHAR : parameterMapping.getJdbcType());
                }
            }
        }
    }

    /**
     * 根据数据库方言，生成特定的分页sql.
     *
     * @param sql        要查询的sql语句
     * @param pagination 分页参数
     * @return 生成带分页的sql语句
     */
    private String generatePageSql(String sql, Pagination pagination) {
        if (pagination != null && StringUtils.hasLength(dialect)) {
            StringBuffer pageSql = new StringBuffer();
            if (MYSQL.equals(dialect)) {
                pageSql.append(sql);
                pageSql.append(" limit " + pagination.getCurrentResult() + "," + pagination
                        .getPageSize());
            } else if (ORACLE.equals(dialect)) {
                pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from (");
                pageSql.append(sql);
                pageSql.append(") tmp_tb where ROWNUM<=");
                pageSql.append(pagination.getCurrentResult() + pagination.getPageSize());
                pageSql.append(") where row_id>");
                pageSql.append(pagination.getCurrentResult());
            }
            return pageSql.toString();
        } else {
            return sql;
        }
    }

    @Override
    public Object plugin(Object target) {
        // 当目标类是StatementHandler类型时，才包装目标类，否者直接返回目标本身,减少目标被代理的次数
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {
    }


}
